package com.msb.crm.service;

import com.msb.crm.base.BaseService;
import com.msb.crm.dao.ModuleMapper;
import com.msb.crm.dao.PermissionMapper;
import com.msb.crm.model.TreeModel;
import com.msb.crm.utils.AssertUtil;
import com.msb.crm.vo.Module;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ModuleService extends BaseService<Module,Integer> {


    @Autowired
    private ModuleMapper moduleMapper;

    @Autowired
    private PermissionMapper permissionMapper;



    /**
     * 查询所有Modules
     * @return
     */
    public List<TreeModel> queryAllModules(Integer roleId){
        List<TreeModel> treeModels = moduleMapper.queryAllModules();

        //根据角色id 查询角色拥有的菜单id
        List<Integer> roleHasMids = permissionMapper.queryRoleHasAllModuleIdsByRoleId(roleId);
        if (null != roleHasMids && roleHasMids.size()>0){
            treeModels.forEach(treeModel -> {
                if (roleHasMids.contains(treeModel.getId())){
                    //说明当前角色 分配了该菜单
                    treeModel.setChecked(true);
                }
            });
        }
        return treeModels;
    }

    /**
     * 查询所有资源
     * @return
     */
    public Map<String,Object> moduleList(){
        Map<String ,Object> result = new HashMap<>();
        List<Module> modules = moduleMapper.queryModules();
        result.put("count",modules.size());
        result.put("data",modules);
        result.put("code",0);
        result.put("msg","");
        return result;
    }


    /**
     * 资源记录添加
     * @param module
     */
    @Transactional
    public void saveModule(Module module){
        //参数校验
        AssertUtil.isTrue(StringUtils.isBlank(module.getModuleName()),"请输入菜单名!");
        Integer grade = module.getGrade();
        AssertUtil.isTrue(null == grade || !(grade==0||grade==1||grade==2),"菜单层级不合法!");
        Module temp = moduleMapper.queryModuleByGradeAndModuleName(grade,module.getModuleName());
        if (null != temp){
            AssertUtil.isTrue(!(temp.getId().equals(module.getId())),"该层级下菜单已存在!");
        }
        if (grade != 0){
            Integer parentId = module.getParentId();
            AssertUtil.isTrue(null == parentId || selectByPrimaryKey(parentId) == null,"请指定上级菜单!");

        }
        if (grade == 1){
            AssertUtil.isTrue(StringUtils.isBlank(module.getUrl()),"请指定二级菜单url值");
            temp = moduleMapper.queryModuleByGradeAndUrl(grade,module.getUrl());
            if (null != temp){
                AssertUtil.isTrue(!(temp.getId().equals(module.getId())),"该层级下url已存在!");
            }
        }

        AssertUtil.isTrue(StringUtils.isBlank(module.getOptValue()),"请输入权限码!");
        AssertUtil.isTrue(null !=moduleMapper.queryModuleByOptvalue(module.getOptValue()),"权限码重复!");
        module.setIsValid((byte)1);
        module.setCreateDate(new Date());
        module.setUpdateDate(new Date());
        AssertUtil.isTrue(insertSelective(module)<1,"菜单添加失败!");
    }


    /**
     * 资源记录更新
     * @param module
     */
    @Transactional
    public void updateModule(Module module){

        //参数校验
        AssertUtil.isTrue(null == module.getId() || null == selectByPrimaryKey(module.getId()),"待更新记录不存在!");
        AssertUtil.isTrue(StringUtils.isBlank(module.getModuleName()),"请输入菜单名!");
        Integer grade = module.getGrade();
        AssertUtil.isTrue(null == grade || !(grade==0||grade==1||grade==2),"菜单层级不合法!");
        Module temp = moduleMapper.queryModuleByGradeAndModuleName(grade,module.getModuleName());
        if (null != temp){
            AssertUtil.isTrue(!(temp.getId().equals(module.getId())),"该层级下菜单已存在!");
        }
        if (grade != 0){
            Integer parentId = module.getParentId();
            AssertUtil.isTrue(null == parentId || selectByPrimaryKey(parentId) == null,"请指定上级菜单!");

        }
        if (grade == 1){
            AssertUtil.isTrue(StringUtils.isBlank(module.getUrl()),"请指定二级菜单url值");
            temp = moduleMapper.queryModuleByGradeAndUrl(grade,module.getUrl());
            if (null != temp){
                AssertUtil.isTrue(!(temp.getId().equals(module.getId())),"该层级下url已存在!");
            }
        }

        AssertUtil.isTrue(StringUtils.isBlank(module.getOptValue()),"请输入权限码!");
        if (null != temp){
            AssertUtil.isTrue(!(temp.getId().equals(module.getId())),"权限码已存在!");
        }

        module.setUpdateDate(new Date());
        AssertUtil.isTrue(updateByPrimaryKeySelective(module)<1,"菜单更新失败!");
    }


    /**
     * 删除资源
     * @param mid
     */
    @Transactional
    public void deleteModuleById(Integer mid){
        Module temp = selectByPrimaryKey(mid);
        AssertUtil.isTrue(null == mid || null == temp,"待删除记录不存在!");

        /*如果存在子项就不允许删除*/
        int count = moduleMapper.countSubModuleByParentId(mid);
        AssertUtil.isTrue(count > 0,"存在子菜单，不支持删除操作!");

        //权限表
        count = permissionMapper.countPermissionByModuleId(mid);
        if (count > 0){
            AssertUtil.isTrue(permissionMapper.deletePermissionsByModuleId(mid)<count,"菜单删除失败!");
        }
        temp.setIsValid((byte) 0);
        AssertUtil.isTrue(updateByPrimaryKeySelective(temp)<1,"菜单删除失败!");
    }

}
